<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <!-- 上传图片进度条 -->

      <el-progress
        v-if="showProgress"
        type="circle"
        class="progress"
        :percentage="percentage"
      />
    </el-upload>
  </div>
</template>

<script>
// 导入 cos 模块
const COS = require('cos-js-sdk-v5')

var cos = new COS({
  SecretId: 'AKIDrVu2u42lEQN5brsfCTUGm14rOedKlwqW',
  SecretKey: 'UjiR3PWNyKQGqBG5ez4tTnshFZfV5PUI'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      showProgress: false, // 图片上传进度条状态
      percentage: 0
    }
  },
  methods: {
    upload(files) {
      console.log(files)
      if (files.file) {
        cos.putObject(
          {
            Bucket: 'sunxiaohui-1308159377', // 存储桶的名称，必须
            Region: 'ap-beijing', // 存储桶所在地域，必须字段
            Key: files.file.name, // 文件名，必须
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: files.file, // 上传文件对象
            // 上传进度条
            onProgress: function(progressData) {
              this.percentage = progressData.percent * 100
            }
          },
          (err, data) => {
            if (err === null && data.statusCode === 200) {
              this.imageUrl = `https:${data.Location}`
            }
          }
        )
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {}
  }
}
</script>

  <style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
